package com.hhq.common.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hhq.common.domain.vo.CommonResultVO;
import com.hhq.common.enums.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * <p>Description: some description </p>
 *
 * @author : xiaodong.yang
 * @date : 2023/11/10 14:20
 */
@Slf4j
public class HttpUtil {


    /**
     * 获取request
     *
     * @return
     */
    public static HttpServletRequest request() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getRequest();
    }

    /**
     * 处理response
     *
     * @param response
     * @param status
     * @param data
     */
    public static void response(HttpServletResponse response, int status, Object data) {
        ObjectMapper objectMapper = new ObjectMapper();
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        response.setStatus(status);
        try (PrintWriter out = response.getWriter()) {
            CommonResultVO<Object> resultVO = new CommonResultVO<>();
            resultVO.setCode(ResultEnum.BUSINESS_ERROR.getCode());
            resultVO.setData(data);
            out.write(objectMapper.writeValueAsString(resultVO));
        } catch (Exception e) {
            log.error("系统异常", e);
        }
    }

}
